package com.itcast.googleplay.holder;

import java.io.File;
import com.itcast.googleplay.R;
import com.itcast.googleplay.bean.AppInfo;
import com.itcast.googleplay.http.HttpApi;
import com.itcast.googleplay.ui.ProgressArc;
import com.itcast.googleplay.utils.UIUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.HttpHandler.State;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.sample.download.DownloadInfo;
import com.lidroid.xutils.sample.download.DownloadManager;
import com.lidroid.xutils.sample.download.DownloadService;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RatingBar;
import android.widget.TextView;

public class HomeHolder extends BaseHolder<AppInfo>{
	private static final String TAG = "HomeHolder";
	private AppInfo appInfo;
	private ImageView ivIcon;
	private TextView tvName,tvSize,tvDes;
	private RatingBar ratingBar;
	private DisplayImageOptions options;
	
	private ProgressArc pbArc;
	private TextView tvState;
	
	private DownloadStateListener downloadStateListener = new DownloadStateListener();
	private DownloadManager downloadManager = DownloadService.getDownloadManager(UIUtils.getContext());
	
	class DownloadStateListener extends RequestCallBack<File> {
		
		@Override
		public void onFailure(HttpException arg0, String progress) {
			// 下载失败
			refreshUI();
		}

		@Override
		public void onSuccess(ResponseInfo<File> file) {
			// 下载成功
			refreshUI();
		}

		@Override
		public void onLoading(long total, long current, boolean isUploading) {
			System.out.println("onLoading........");
			// 下载过程中
			refreshUI();
			super.onLoading(total, current, isUploading);
		}

		@Override
		public void onStart() {
			// 开始下载
			refreshUI();
			super.onStart();
		}

		@Override
		public void onCancelled() {
			// 下载取消
			refreshUI();
			super.onCancelled();
		}
	}
	
	public void refreshUI() {
		DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(appInfo.getId() + "");
		
		if (downloadInfo == null) {
			Log.i(TAG, " if 文件名称 appInfo.name = "+appInfo.name);
			
			tvState.setText("下载");
			
			pbArc.setStyle(ProgressArc.PROGRESS_STYLE_NO_PROGRESS);
			pbArc.setBackgroundResource(R.drawable.ic_download);
		} else {
			Log.i(TAG, "else 文件名称 downloadInfo.getFileName = "+downloadInfo.getFileName());
			String appId = downloadInfo.getAppId();
			if (Integer.parseInt(appId) == appInfo.getId()) {
				switch (downloadInfo.getState()) {
				case CANCELLED:
//					pbProgress.setProgress(progress);
					pbArc.setStyle(ProgressArc.PROGRESS_STYLE_NO_PROGRESS);
					pbArc.setBackgroundResource(R.drawable.ic_resume);
					tvState.setText("继续");
					break;
				case FAILURE:
					pbArc.setStyle(ProgressArc.PROGRESS_STYLE_NO_PROGRESS);
					pbArc.setBackgroundResource(R.drawable.ic_redownload);
					tvState.setText("重试");
					break;
				case LOADING:
					if(downloadInfo.getFileLength()>0){
						int progressloading = (int) (
								downloadInfo.getProgress() * 100 / downloadInfo.getFileLength());
//						pbProgress.setProgress(progressloading);
						pbArc.setStyle(ProgressArc.PROGRESS_STYLE_DOWNLOADING);
						pbArc.setBackgroundResource(R.drawable.ic_pause);
						float progress = (downloadInfo.getProgress()+0.0f)/downloadInfo.getFileLength();
						pbArc.setProgress(progress, true);
						tvState.setText(progressloading + "%");
					}
					break;
				case STARTED:
					pbArc.setStyle(ProgressArc.PROGRESS_STYLE_NO_PROGRESS);
					pbArc.setBackgroundResource(R.drawable.ic_download);
					tvState.setText("准备下载");
					break;
				case SUCCESS:
					tvState.setText("安装");
//					pbProgress.setProgress(100);
					pbArc.setStyle(ProgressArc.PROGRESS_STYLE_NO_PROGRESS);
					pbArc.setBackgroundResource(R.drawable.ic_install);
					break;
				case WAITING:
					tvState.setText("等待");
					pbArc.setStyle(ProgressArc.PROGRESS_STYLE_NO_PROGRESS);
					pbArc.setBackgroundResource(R.drawable.ic_download);
					break;
				default:
					tvState.setText("等待");
					pbArc.setStyle(ProgressArc.PROGRESS_STYLE_NO_PROGRESS);
					pbArc.setBackgroundResource(R.drawable.ic_download);
					break;
				}
			}
		}
	}

	@Override
	public void initData() {
		options = new DisplayImageOptions.Builder()
			.showImageOnLoading(R.drawable.ic_default)
			.showImageForEmptyUri(R.drawable.ic_default)
			.showImageOnFail(R.drawable.ic_default)
			.cacheInMemory(true)
			.cacheOnDisk(true)
			.considerExifParams(true)//是否允许让图片反转
			.build();
		
	
		
		appInfo = getData();
		
//		registerListenerAgain();
		
		tvName.setText(appInfo.name);
		ratingBar.setRating(appInfo.stars);
		tvSize.setText(Formatter.formatFileSize(UIUtils.getContext(), appInfo.size));
		tvDes.setText(appInfo.des);
		
		ImageLoader.getInstance().displayImage(HttpApi.IMAGEURL+appInfo.getIconUrl(), ivIcon, options);
		
		refreshUI();
	}

	@Override
	public View initView() {
		View view = UIUtils.inflate(R.layout.list_item);
		ivIcon = (ImageView) view.findViewById(R.id.iv_icon);
		tvName = (TextView) view.findViewById(R.id.tv_name);
		ratingBar = (RatingBar) view.findViewById(R.id.ratingbar);
		tvSize = (TextView) view.findViewById(R.id.tv_size);
		tvDes = (TextView) view.findViewById(R.id.tv_des);
		
		pbArc = new ProgressArc(UIUtils.getContext());
		
		pbArc.setArcDiameter(UIUtils.dip2px(28));
		pbArc.setProgressColor(UIUtils.getColor(R.color.progress));
		
		FrameLayout flContainer = (FrameLayout) view.findViewById(R.id.fl_container);
		FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams
			(UIUtils.dip2px(30),UIUtils.dip2px(30));
		flContainer.addView(pbArc, layoutParams);
		
		tvState = (TextView) view.findViewById(R.id.tv_state);
		
		flContainer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				download();
			}
		});
		return view;
	}

	protected void download() {
		// sd卡被挂载
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// 获取sd卡路径
			String target = Environment.getExternalStorageDirectory()
					+File.separator +"GooglePlay"
					+File.separator+"download"
					+File.separator+appInfo.packageName + ".apk";
					
			DownloadInfo downloadInfo = downloadManager
					.getDownloadInfoByAppId(appInfo.getId() + "");

			if (downloadInfo != null) {
				// 断点续传下载
				HttpHandler.State state = downloadInfo.getState();
				switch (state) {
				case WAITING:// 等待状态的时候,点击后取消下载
//					break;
				case STARTED:// 准备开始的时候,点击后取消下载
				case LOADING:// 正在下载的时候,点击后取消下载
					try {
						downloadManager.stopDownload(downloadInfo);
					} catch (DbException e) {
						e.printStackTrace();
					}
					break;
				case CANCELLED:// 取消下载,点击后继续下载
				case FAILURE:// 下载失败,点击后继续下载
					try {
						downloadManager.resumeDownload(downloadInfo,
								downloadStateListener);
					} catch (DbException e) {
						e.printStackTrace();
					}
					break;
				case SUCCESS:
					// 下载成功,点击后安装apk
					installApk();
					break;
				}
			} else {
				// 重头开始下载
				try {
					downloadManager.addNewDownload(
							appInfo.getId() + "",
							HttpApi.BASEURL + "download?name="
									+ appInfo.getDownloadUrl(), appInfo.name, target,
							true, false, downloadStateListener);
					
				} catch (DbException e) {
					e.printStackTrace();
				}
			}
			UIUtils.runInMainThread(new Runnable() {
				@Override
				public void run() {
					refreshUI();
				}
			});
		}
	}
	
	private void installApk() {
		Intent intent = new Intent("android.intent.action.VIEW");
		//匹配category
		intent.addCategory("android.intent.category.DEFAULT");
		//匹配data数据源
		//匹配数据类型
		DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(appInfo.id+"");
		intent.setDataAndType(Uri.parse("file://"+downloadInfo.getFileSavePath()),
				"application/vnd.android.package-archive");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		UIUtils.getContext().startActivity(intent);
	}
	
	@Override
	public View getConvertView() {
		Log.i(TAG, "刷新了adapter.............");
		registerListenerAgain();
		return super.getConvertView();
	}

	private void registerListenerAgain() {
		if(appInfo!=null){
			DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(appInfo.getId()+"");
			if(downloadInfo!=null){
		         if (downloadInfo.getHandler() != null) {
		             RequestCallBack callBack = downloadInfo.getHandler().getRequestCallBack();
		             if (callBack instanceof DownloadManager.ManagerCallBack) {
		                 DownloadManager.ManagerCallBack managerCallBack = (DownloadManager.ManagerCallBack) callBack;
		                 managerCallBack.setBaseCallBack(downloadStateListener);
		             }
		         }
			}
		}
	}

	public void cancelDownload() {
		DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(appInfo.getId()+"");
		try {
			if(downloadInfo!=null){
				State state = downloadInfo.getState();
				if(state == State.WAITING || state == State.LOADING || state == State.STARTED){
					downloadManager.stopDownload(downloadInfo);
				}
			}
		} catch (DbException e) {
			e.printStackTrace();
		}
	}
}
